package com.gzc.just.play.last.war.centralserver.connection;

import com.gzc.just.play.last.war.common.connection.NacosAwareConnector;
import com.gzc.just.play.last.war.common.connection.ServerConnectionManager;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;

import jakarta.annotation.PreDestroy;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@Component("central-centralServerConnector")
public class CentralServerConnector extends NacosAwareConnector {
    
    @Value("${scene.server.host:127.0.0.1}")
    private String sceneServerHost;
    
    @Value("${scene.server.port:50001}")
    private int sceneServerPort;
    
    @Value("${login.server.host:127.0.0.1}")
    private String loginServerHost;
    
    @Value("${login.server.port:30001}")
    private int loginServerPort;
    
    @Value("${balance.server.host:127.0.0.1}")
    private String balanceServerHost;
    
    @Value("${balance.server.port:7001}")
    private int balanceServerPort;
    
    @PostConstruct
    public void init() {
        log.info("Initializing CentralServer connections...");
        initializeConnections();
        log.info("CentralServer connections initialization completed");
    }
    
    @Override
    protected Map<String, ServerConnectionManager.ServerType> getDependencies() {
        Map<String, ServerConnectionManager.ServerType> dependencies = new HashMap<>();
        // Nacos服务名与ServerType的映射
        dependencies.put("scene-server", ServerConnectionManager.ServerType.SCENE_SERVER);
        dependencies.put("login-server", ServerConnectionManager.ServerType.LOGIN_SERVER);
        dependencies.put("balance-server", ServerConnectionManager.ServerType.BALANCE_SERVER);
        return dependencies;
    }
    
    @Override
    protected void initializeWithStaticConfig() {
        log.info("Initializing with static configuration (Nacos disabled)");
        
        connectionManager.registerServerConfig(
                ServerConnectionManager.ServerType.SCENE_SERVER,
                new ServerConnectionManager.ServerConfig(sceneServerHost, sceneServerPort)
        );
        
        connectionManager.registerServerConfig(
                ServerConnectionManager.ServerType.LOGIN_SERVER,
                new ServerConnectionManager.ServerConfig(loginServerHost, loginServerPort)
        );
        
        connectionManager.registerServerConfig(
                ServerConnectionManager.ServerType.BALANCE_SERVER,
                new ServerConnectionManager.ServerConfig(balanceServerHost, balanceServerPort)
        );
        
        // 延迟建立连接以确保服务器先启动（all-in-one模式兼容）
        if (isAllInOneMode()) {
            log.info("Detected all-in-one mode, delaying connection establishment...");
            // 可以使用线程池延迟建立连接
        } else {
            establishConnections();
        }
        
        connectionManager.startHeartbeat();
    }
    
    private void establishConnections() {
        connectionManager.connectToServer(ServerConnectionManager.ServerType.SCENE_SERVER)
                .thenAccept(channel -> log.info("Connected to SceneServer"))
                .exceptionally(throwable -> {
                    log.error("Failed to connect to SceneServer", throwable);
                    return null;
                });
        
        connectionManager.connectToServer(ServerConnectionManager.ServerType.LOGIN_SERVER)
                .thenAccept(channel -> log.info("Connected to LoginServer"))
                .exceptionally(throwable -> {
                    log.error("Failed to connect to LoginServer", throwable);
                    return null;
                });
        
        connectionManager.connectToServer(ServerConnectionManager.ServerType.BALANCE_SERVER)
                .thenAccept(channel -> log.info("Connected to BalanceServer"))
                .exceptionally(throwable -> {
                    log.error("Failed to connect to BalanceServer", throwable);
                    return null;
                });
    }
    
    /**
     * 检查是否为all-in-one模式
     * @return 是否为all-in-one模式
     */
    private boolean isAllInOneMode() {
        String activeProfile = System.getProperty("spring.profiles.active", "");
        return activeProfile.contains("allinone") || activeProfile.contains("dev-all-in-one");
    }

    @PreDestroy
    public void shutdown() {
        log.info("Shutting down CentralServer connections...");
        shutdownConnections();
        log.info("CentralServer connections shutdown completed");
    }
}
